﻿using System;
using System.Text;
using System.Linq;
using Dapper;
using Dapper.Contrib.Extensions;

namespace EC.Application.Impl
{

    using EC.Application.Interface;

    using EC.Entity;
    using EC.Entity.Enum;
    using EC.Entity.Query;
    using EC.Entity.Request.Business;
    using EC.Entity.Request.Merchant;
    using EC.Entity.Request.Token;
    using EC.Entity.Response.Merchant;
    using EC.Entity.Response.Token;
    using EC.Entity.Tables;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;

    /// <summary>
    /// 
    /// </summary>
    public class MerchantServiceImpl : MerchantService
    {
        #region 注入
        /// <summary>
        /// 数据接口
        /// </summary>
        private readonly IDBSession _dbSession;


        /// <summary>
        /// 数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public MerchantServiceImpl(IDBSession dbSession)
        {
            _dbSession = dbSession;
        }
        #endregion

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public MerchantResponse Get(int id)
        {
            var merchants = _dbSession.DbConnection.Query<MerchantResponse>("select * from merchant where Id=@Id", new { Id = id });

            var merchant = merchants.FirstOrDefault();
            if (merchant != null)
            {
                return merchant;
            }
            return null;
        }

        /// <summary>
        /// 根据商户ID获取Token
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public List<MerchantResponse> GetMerchantByIds(List<int> ids)
        {
            var list = _dbSession.DbConnection.Query<MerchantResponse>($"select * from merchant where Id in({ string.Join(", ", ids)})");

            return list.ToList();
        }

        /// <summary>
        /// 根据商户ID获取Token
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public TokenResponse GetToken(int merchantId)
        {

            var tokens = _dbSession.DbConnection.Query<TokenResponse>("select * from token where MerchantId=@MerchantId", new { MerchantId = merchantId });

            var token = tokens.FirstOrDefault();
            if (token != null)
            {
                return token;
            }

            return null;
        }

        /// <summary>
        /// 根据商户ID获取Token
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public List<MerchantResponse> GetType(int type)
        {

            var list = _dbSession.DbConnection.Query<MerchantResponse>("select * from merchant where Type=@Type", new { Type = type });

            return list.ToList();
        }

        /// <summary>
        /// 设置代理
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveProxy(SaveProxyRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where id=@MerchantId", new { MerchantId = request.MerchantId });

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    throw new Exception("商户不存在");
                }

                if (request.ProxyId == null)
                {
                    merchant.ProxyId = "";
                }
                else
                {
                    merchant.ProxyId = string.Join(", ", request.ProxyId);
                }
                //更新
                _dbSession.DbConnection.Update<Merchant>(merchant);

                response.Success = true;
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// Token新增、编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveToken(SaveTokenRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var tokens = _dbSession.DbConnection.Query<Token>("select * from token where MerchantId=@MerchantId", new { MerchantId = request.MerchantId });

                var token = tokens.FirstOrDefault();
                if (token == null)
                {
                    var model = new Token()
                    {
                        MerchantId = request.MerchantId,
                        AppId = request.AppId,
                        AppSecret = request.AppSecret,
                        Status = request.Status,
                    };

                    //新增
                    long resultId = _dbSession.DbConnection.Insert<Token>(model);

                    if (resultId <= 0)
                    {
                        throw new Exception("新增Token失败.");
                    }
                    response.Success = true;
                }
                else
                {
                    token.AppId = request.AppId;
                    token.AppSecret = request.AppSecret;
                    token.Status = request.Status;

                    //更新
                    _dbSession.DbConnection.Update<Token>(token);

                    response.Success = true;
                }
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveRecharge(BalanceRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                //充值金额
                if (string.IsNullOrEmpty(request.Amount))
                {
                    return new JResult()
                    {
                        Success = false,
                        Message = "充值金额不能为空."
                    };
                }

                decimal amount;
                try
                {
                    amount = Convert.ToDecimal(request.Amount);
                }
                catch (Exception)
                {
                    return new JResult()
                    {
                        Success = false,
                        Message = "提款金额货币格式有误"
                    };
                }

                if (amount <= 0)
                {
                    return new JResult()
                    {
                        Success = false,
                        Message = "充值金额必须大于零."
                    };
                }
                //事务开始
                _dbSession.Begin();

                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = request.MerchantId }, _dbSession.DbTransaction);

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    throw new Exception("暂无记录.");
                }

                //减去存款余额日志
                var depositBalanceLog = new BalanceLog()
                {
                    MerchantId = request.MerchantId,
                    Source = (int)BalanceLogSource.充值,
                    Type = (int)BalanceLogType.加,
                    Amount = amount,
                    BeforeBalance = merchant.DepositBalance,
                    AfterBalance = merchant.DepositBalance + amount,
                    Remark = "充值",
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };

                //新增
                long depositBalanceLogResultId = _dbSession.DbConnection.Insert<BalanceLog>(depositBalanceLog, _dbSession.DbTransaction);

                if (depositBalanceLogResultId <= 0)
                {
                    throw new Exception("新增日志失败.");
                }

                //余额
                int result = _dbSession.DbConnection.Execute("UPDATE merchant SET DepositBalance=DepositBalance+@Amount WHERE Id=@Id", new { Amount = amount, Id = request.MerchantId }, _dbSession.DbTransaction);
                if (result <= 0)
                {
                    throw new Exception("更新账户失败");
                }

                response.Success = true;
                //提交事务
                _dbSession.Commit();
            }
            catch (Exception ex)
            {
                _dbSession.Rollback();

                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 充值(带手续费)
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveRechargeFee(BalanceRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                //充值金额
                if (string.IsNullOrEmpty(request.Amount))
                {
                    return new JResult()
                    {
                        Success = false,
                        Message = "充值金额不能为空."
                    };
                }

                decimal amount;
                try
                {
                    amount = Convert.ToDecimal(request.Amount);
                }
                catch (Exception)
                {
                    return new JResult()
                    {
                        Success = false,
                        Message = "充值金额货币格式有误"
                    };
                }

                if (amount <= 0)
                {
                    return new JResult()
                    {
                        Success = false,
                        Message = "充值金额必须大于零."
                    };
                }
                //事务开始
                _dbSession.Begin();

                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = request.MerchantId }, _dbSession.DbTransaction);

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    throw new Exception("暂无记录.");
                }

                if (merchant.PaymentRate <= 0)
                {
                    throw new Exception("内充汇率未设置.");
                }

                var total = amount - (amount * merchant.PaymentRate);
                //充值记录
                var recharge = new Recharge()
                {
                    MerchantId = request.MerchantId,
                    Amount = total,
                    Fee = amount * merchant.PaymentRate,
                    BeforeBalance = merchant.DepositBalance,
                    AfterBalance = merchant.DepositBalance + total,
                    Remark = $"系统充值 手续费{amount * merchant.PaymentRate}",
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };

                long rechargeResultId = _dbSession.DbConnection.Insert<Recharge>(recharge, _dbSession.DbTransaction);

                if (rechargeResultId <= 0)
                {
                    throw new Exception("新增充值记录失败.");
                }

                //减去存款余额日志
                var depositBalanceLog = new BalanceLog()
                {
                    MerchantId = request.MerchantId,
                    OrderNo = Convert.ToInt32(rechargeResultId),
                    Source = (int)BalanceLogSource.充值带手续费,
                    Type = (int)BalanceLogType.加,
                    Amount = total,
                    BeforeBalance = merchant.DepositBalance,
                    AfterBalance = merchant.DepositBalance + total,
                    Remark = $"系统充值 手续费{amount * merchant.PaymentRate}",
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };

                //新增
                long depositBalanceLogResultId = _dbSession.DbConnection.Insert<BalanceLog>(depositBalanceLog, _dbSession.DbTransaction);

                if (depositBalanceLogResultId <= 0)
                {
                    throw new Exception("新增日志失败.");
                }

                //余额
                int result = _dbSession.DbConnection.Execute("UPDATE merchant SET DepositBalance=DepositBalance+@Amount WHERE Id=@Id", new { Amount = total, Id = request.MerchantId }, _dbSession.DbTransaction);
                if (result <= 0)
                {
                    throw new Exception("更新账户失败");
                }

                response.Success = true;
                //提交事务
                _dbSession.Commit();
            }
            catch (Exception ex)
            {
                _dbSession.Rollback();

                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 扣减余额
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveLessBalance(BalanceRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                //充值金额
                if (string.IsNullOrEmpty(request.Amount))
                {
                    return new JResult()
                    {
                        Success = false,
                        Message = "充值金额不能为空."
                    };
                }

                decimal amount;
                try
                {
                    amount = Convert.ToDecimal(request.Amount);
                }
                catch (Exception)
                {
                    return new JResult()
                    {
                        Success = false,
                        Message = "充值金额货币格式有误"
                    };
                }

                if (amount <= 0)
                {
                    return new JResult()
                    {
                        Success = false,
                        Message = "扣减金额必须大于零."
                    };
                }
                //事务开始
                _dbSession.Begin();

                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = request.MerchantId }, _dbSession.DbTransaction);

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    throw new Exception("暂无记录.");
                }


                //减去存款余额日志
                var depositBalanceLog = new BalanceLog()
                {
                    MerchantId = request.MerchantId,
                    Source = (int)BalanceLogSource.扣减余额,
                    Type = (int)BalanceLogType.减,
                    Amount = amount,
                    BeforeBalance = merchant.DepositBalance,
                    AfterBalance = merchant.DepositBalance - amount,
                    Remark = $"扣除余额",
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };

                //新增
                long depositBalanceLogResultId = _dbSession.DbConnection.Insert<BalanceLog>(depositBalanceLog, _dbSession.DbTransaction);

                if (depositBalanceLogResultId <= 0)
                {
                    throw new Exception("新增日志失败.");
                }

                //余额
                int result = _dbSession.DbConnection.Execute("UPDATE merchant SET DepositBalance=DepositBalance-@Amount WHERE Id=@Id", new { Amount = amount, Id = request.MerchantId }, _dbSession.DbTransaction);
                if (result <= 0)
                {
                    throw new Exception("更新账户失败");
                }

                response.Success = true;
                //提交事务
                _dbSession.Commit();
            }
            catch (Exception ex)
            {
                _dbSession.Rollback();

                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 提现
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveWithdrawal(SaveWithdrawalRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            //银行名字
            if (string.IsNullOrEmpty(request.BankName))
            {
                return new JResult()
                {
                    Success = false,
                    Message = "银行名字不能为空."
                };
            }
            //银行名字
            if (string.IsNullOrEmpty(request.CardName))
            {
                return new JResult()
                {
                    Success = false,
                    Message = "姓名不能为空."
                };
            }
            //卡号
            if (string.IsNullOrEmpty(request.CardNumber))
            {
                return new JResult()
                {
                    Success = false,
                    Message = "卡号不能为空."
                };
            }
            //金额
            if (string.IsNullOrEmpty(request.Amount))
            {
                return new JResult()
                {
                    Success = false,
                    Message = "金额不能为空."
                };
            }

            var paymentRateReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,3})?$");
            if (!paymentRateReg.IsMatch(request.Amount))
            {
                return new JResult()
                {
                    Success = false,
                    Message = "充值金额最大保留三位小数，整数最多保留两位."
                };
            }

            var amount = Convert.ToDecimal(request.Amount);
            if (amount <= 0)
            {
                return new JResult()
                {
                    Success = false,
                    Message = "充值金额必须大于零."
                };
            }

            try
            {
                //事务开始
                _dbSession.Begin();

                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = request.MerchantId }, _dbSession.DbTransaction);

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    throw new Exception("暂无记录.");
                }

                var total = amount + merchant.SettleSingle;

                //验证
                if (merchant.DepositBalance < total)
                {
                    throw new Exception("余额不足.");
                }


                //增加结算记录
                var settle = new Settle()
                {
                    MerchantId = request.MerchantId,
                    BankName = request.BankName,
                    CardName = request.CardName,
                    CardNumber = request.CardNumber,
                    Amount = total,
                    Fee = merchant.SettleSingle,
                    Status = (int)SettleStatus.未处理,
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };

                long settleResultId = _dbSession.DbConnection.Insert<Settle>(settle, _dbSession.DbTransaction);

                if (settleResultId <= 0)
                {
                    throw new Exception("新增结算失败.");
                }
                //日志
                //减去存款余额日志
                var depositBalanceLog = new BalanceLog()
                {
                    MerchantId = request.MerchantId,
                    Source = (int)BalanceLogSource.存款余额,
                    Type = (int)BalanceLogType.减,
                    Amount = settle.Amount,
                    BeforeBalance = merchant.DepositBalance,
                    AfterBalance = merchant.DepositBalance - total,
                    Remark = "提现",
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };
                //新增
                long depositBalanceLogResultId = _dbSession.DbConnection.Insert<BalanceLog>(depositBalanceLog, _dbSession.DbTransaction);

                if (depositBalanceLogResultId <= 0)
                {
                    throw new Exception("新增减去存款余额日志失败.");
                }
                //余额
                int result = _dbSession.DbConnection.Execute("UPDATE merchant SET DepositBalance=DepositBalance-@Amount WHERE Id=@Id and DepositBalance>@Amount", new { Amount = total, Id = request.MerchantId }, _dbSession.DbTransaction);
                if (result <= 0)
                {
                    throw new Exception("更新账户失败");
                }

                response.Success = true;
                //提交事务
                _dbSession.Commit();
            }
            catch (Exception ex)
            {
                _dbSession.Rollback();

                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 冻结余额
        /// </summary>
        /// <returns></returns>
        public JResult SaveFrozenBalance(BalanceRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            //金额
            if (string.IsNullOrEmpty(request.Amount))
            {
                return new JResult()
                {
                    Success = false,
                    Message = "金额不能为空."
                };
            }

            decimal amount;
            try
            {
                amount = Convert.ToDecimal(request.Amount);
            }
            catch (Exception)
            {
                return new JResult()
                {
                    Success = false,
                    Message = "金额格式有误."
                };
            }

            if (amount <= 0)
            {
                return new JResult()
                {
                    Success = false,
                    Message = "冻结余额必须大于零."
                };
            }
            try
            {
                //事务开始
                _dbSession.Begin();

                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = request.MerchantId }, _dbSession.DbTransaction);

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    throw new Exception("暂无记录.");
                }

                //验证
                if (merchant.DepositBalance < amount)
                {
                    throw new Exception("余额不足.");
                }

                //冻结日志
                var frozenBalanceLog = new FrozenBalanceLog()
                {
                    MerchantId = request.MerchantId,
                    Source = (int)FrozenBalanceLogSource.存款余额,
                    Amount = amount,
                    Remark = request.Remark,
                    Status = (int)FrozenBalanceLogStatus.冻结,
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };

                long frozenBalanceLogId = _dbSession.DbConnection.Insert<FrozenBalanceLog>(frozenBalanceLog, _dbSession.DbTransaction);

                if (frozenBalanceLogId <= 0)
                {
                    throw new Exception("新增余额冻结失败.");
                }
                //余额
                int result = _dbSession.DbConnection.Execute("UPDATE merchant SET DepositBalance=DepositBalance-@Amount,DepositFrozenBalance=DepositFrozenBalance+@Amount WHERE Id=@Id and DepositBalance>@Amount", new { Amount = amount, Id = request.MerchantId }, _dbSession.DbTransaction);
                if (result <= 0)
                {
                    throw new Exception("更新账户失败");
                }
                //减去存款余额日志
                var depositBalanceLog = new BalanceLog()
                {
                    MerchantId = request.MerchantId,
                    Source = (int)BalanceLogSource.余额冻结,
                    Type = (int)BalanceLogType.减,
                    Amount = amount,
                    BeforeBalance = merchant.DepositBalance,
                    AfterBalance = merchant.DepositBalance - amount,
                    Remark = $"存款余额冻结,{request.Remark}",
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };
                long depositBalanceLogResultId = _dbSession.DbConnection.Insert<BalanceLog>(depositBalanceLog, _dbSession.DbTransaction);

                if (depositBalanceLogResultId <= 0)
                {
                    throw new Exception("新增日志失败.");
                }
                response.Success = true;
                //提交事务
                _dbSession.Commit();
            }
            catch (Exception ex)
            {
                _dbSession.Rollback();

                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 解冻
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult Thaw(ThawRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                //事务开始
                _dbSession.Begin();

                var frozenBalanceLogs = _dbSession.DbConnection.Query<FrozenBalanceLog>("select * from frozenbalancelog where Id=@Id", new { Id = request.Id }, _dbSession.DbTransaction);
                var frozenBalanceLog = frozenBalanceLogs.FirstOrDefault();
                if (frozenBalanceLog == null)
                {
                    throw new Exception("暂无记录.");
                }

                //商户
                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = frozenBalanceLog.MerchantId }, _dbSession.DbTransaction);

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    throw new Exception("暂无记录.");
                }

                //更新当前记录
                int frozenBalanceLogResult = _dbSession.DbConnection.Execute("UPDATE frozenbalancelog SET Status=@Status WHERE Id=@Id", new { Status = (int)FrozenBalanceLogStatus.解冻, Id = frozenBalanceLog.Id }, _dbSession.DbTransaction);
                if (frozenBalanceLogResult <= 0)
                {
                    throw new Exception("更新冻结记录失败");
                }
                //余额
                int result = _dbSession.DbConnection.Execute("UPDATE merchant SET DepositBalance=DepositBalance+@Amount,DepositFrozenBalance=DepositFrozenBalance-@Amount WHERE Id=@Id and DepositFrozenBalance>=@Amount", new { Amount = frozenBalanceLog.Amount, Id = frozenBalanceLog.MerchantId }, _dbSession.DbTransaction);
                if (result <= 0)
                {
                    throw new Exception("更新账户失败");
                }
                //减去存款余额日志
                var depositBalanceLog = new BalanceLog()
                {
                    MerchantId = merchant.Id,
                    Source = (int)BalanceLogSource.余额解冻,
                    Type = (int)BalanceLogType.加,
                    Amount = frozenBalanceLog.Amount,
                    BeforeBalance = merchant.DepositBalance,
                    AfterBalance = merchant.DepositBalance + frozenBalanceLog.Amount,
                    Remark = $"余额解冻,{request.Remark}",
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };
                long depositBalanceLogResultId = _dbSession.DbConnection.Insert<BalanceLog>(depositBalanceLog, _dbSession.DbTransaction);

                if (depositBalanceLogResultId <= 0)
                {
                    throw new Exception("新增存款余额日志失败.");
                }

                response.Success = true;
                response.Message = "解冻成功";
                //提交事务
                _dbSession.Commit();
            }
            catch (Exception ex)
            {
                _dbSession.Rollback();

                response.Message = ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public List<MerchantResponse> GetList(int type)
        {
            var list = _dbSession.DbConnection.Query<MerchantResponse>("select * from merchant where Type=@Type", new { Type = type }).ToList();

            return list;
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveFinance(SaveMerchantRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (request.Id > 0)
            {
                var merchantNameExist = _dbSession.DbConnection.Query<MerchantResponse>("SELECT * FROM merchant WHERE Name=@Name AND Id!=@Id", new { Name = request.Name, request.Id });
                if (merchantNameExist != null && merchantNameExist.Any())
                {
                    throw new Exception("商户名称已存在.");
                }

                var merchant = _dbSession.DbConnection.QueryFirst<Merchant>("select * from merchant where Id=@Id", new { Id = request.Id });
                if (merchant == null)
                {
                    throw new Exception("商户记录不存在.");
                }
                merchant.Name = request.Name;
                //更新
                _dbSession.DbConnection.Update<Merchant>(merchant);

                response.Success = true;
            }
            else
            {
                var merchantNameExist = _dbSession.DbConnection.Query<MerchantResponse>("SELECT * FROM merchant WHERE Name=@Name", new { Name = request.Name });
                if (merchantNameExist != null && merchantNameExist.Any())
                {
                    throw new Exception("标签名称已存在.");
                }

                var paymentRate = Convert.ToDecimal(request.PaymentRate);
                var depositRate = Convert.ToDecimal(request.DepositRate);
                var depositAliPayRate = Convert.ToDecimal(request.DepositAliPayRate);
                var merchantType = request.Type;

                var merchant = new Merchant()
                {
                    Name = request.Name,
                    PaymentRate = 0,
                    DepositRate = 0,
                    DepositAliPayRate = 0,
                    PaymentSingle = 0,
                    SettleSingle = 0,
                    Type = merchantType,
                    Status = (int)MerchantStatus.启用,
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };

                //新增
                long resultId = _dbSession.DbConnection.Insert<Merchant>(merchant);

                if (resultId <= 0)
                {
                    throw new Exception("商户标签失败.");
                }
                response.Success = true;
            }
            return response;
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult Save(SaveMerchantRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (request.Id > 0)
            {
                var merchantNameExist = _dbSession.DbConnection.Query<MerchantResponse>("SELECT * FROM merchant WHERE Name=@Name AND Id!=@Id", new { Name = request.Name, request.Id });
                if (merchantNameExist != null && merchantNameExist.Any())
                {
                    throw new Exception("商户名称已存在.");
                }

                var merchant = _dbSession.DbConnection.QueryFirst<Merchant>("select * from merchant where Id=@Id", new { Id = request.Id });
                if (merchant == null)
                {
                    throw new Exception("商户记录不存在.");
                }

                var paymentRate = Convert.ToDecimal(request.PaymentRate);
                var depositRate = Convert.ToDecimal(request.DepositRate);
                var depositAliPayRate = Convert.ToDecimal(request.DepositAliPayRate);

                merchant.Name = request.Name;
                merchant.PaymentRate = paymentRate > 0 ? paymentRate / 100 : 0;
                merchant.DepositRate = depositRate > 0 ? depositRate / 100 : 0;
                merchant.DepositAliPayRate = depositAliPayRate > 0 ? depositAliPayRate / 100 : 0;

                merchant.PaymentSingle = Convert.ToInt32(request.PaymentSingle);
                merchant.SettleSingle = Convert.ToInt32(request.SettleSingle);
                merchant.PaymentNotifyUrl = request.PaymentNotifyUrl;
                merchant.DepositNotifyUrl = request.DepositNotifyUrl;
                //更新
                _dbSession.DbConnection.Update<Merchant>(merchant);

                response.Success = true;
            }
            else
            {
                var merchantNameExist = _dbSession.DbConnection.Query<MerchantResponse>("SELECT * FROM merchant WHERE Name=@Name", new { Name = request.Name });
                if (merchantNameExist != null && merchantNameExist.Any())
                {
                    throw new Exception("标签名称已存在.");
                }

                var paymentRate = Convert.ToDecimal(request.PaymentRate);
                var depositRate = Convert.ToDecimal(request.DepositRate);
                var depositAliPayRate = Convert.ToDecimal(request.DepositAliPayRate);

                var merchant = new Merchant()
                {
                    Name = request.Name,
                    PaymentRate = paymentRate > 0 ? paymentRate / 100 : 0,
                    DepositRate = depositRate > 0 ? depositRate / 100 : 0,
                    DepositAliPayRate = depositAliPayRate > 0 ? depositAliPayRate / 100 : 0,
                    PaymentSingle = Convert.ToInt32(request.PaymentSingle),
                    SettleSingle = Convert.ToInt32(request.SettleSingle),
                    PaymentNotifyUrl = request.PaymentNotifyUrl,
                    DepositNotifyUrl = request.DepositNotifyUrl,
                    Type = (int)MerchantType.商户,
                    Status = (int)MerchantStatus.启用,
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };

                //新增
                long resultId = _dbSession.DbConnection.Insert<Merchant>(merchant);

                if (resultId <= 0)
                {
                    throw new Exception("商户标签失败.");
                }
                response.Success = true;
            }
            return response;
        }

        /// <summary>
        /// 状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public JResult UpdateStatus(int id, sbyte status)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var customer = _dbSession.DbConnection.QueryFirst<MerchantResponse>("select * from merchant where Id=@Id", new { Id = id });
                if (customer == null)
                {
                    throw new Exception("商户不存在.");
                }

                var updateSql = "UPDATE merchant SET Status=@Status WHERE Id=@Id";

                int result = _dbSession.DbConnection.Execute(updateSql, new { Status = status, Id = id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }

                response.Success = true;
                response.Message = "操作成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<MerchantQueryResponse> GetPager(MerchantQuery query)
        {
            var currentPageIndex = 0;

            if (query.CurrentPageIndex.Value > 0)
            {
                currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            }

            var files = "Id,Name,PaymentBalance,PaymentFrozenBalance,PaymentProxyFrozenBalance,DepositBalance,DepositFrozenBalance,DepositProxyFrozenBalance,PaymentSingle,SettleSingle,PaymentNotifyUrl,DepositNotifyUrl,PaymentRate,DepositRate,DepositAliPayRate,Type,Status,CreatedBy,CreatedDate";
            var tableName = "merchant";
            var orderby = "ORDER BY Id DESC";
            var where = $"where Id in ({string.Join(", ", query.MerchantIds)})";
            if (query.MerchantIds.Contains(-10000))
            {
                where = $"where 1=1";
            }
            else
            {
                where = $"where Id in ({string.Join(", ", query.MerchantIds)})";
            }

            #region 条件
            if (!string.IsNullOrEmpty(query.Name))
            {
                where += string.Format(" And Name like'%{0}%'", query.Name);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, currentPageIndex, query.PageSize.Value);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<MerchantQueryResponse>();

                return new PagedList<MerchantQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.CurrentPageIndex.Value,
                    TotalCount = count
                };
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<MerchantQueryResponse> GetSyPager(MerchantQuery query)
        {
            var currentPageIndex = 0;

            if (query.CurrentPageIndex.Value > 0)
            {
                currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            }

            var files = "Id,Name,'' as ProxyName,PaymentBalance,PaymentFrozenBalance,PaymentProxyFrozenBalance,DepositBalance,DepositFrozenBalance,DepositProxyFrozenBalance,PaymentSingle,SettleSingle,PaymentNotifyUrl,DepositNotifyUrl,PaymentRate,DepositRate,DepositAliPayRate,Type,ProxyId,Status,CreatedBy,CreatedDate";
            var tableName = "merchant d";
            var orderby = "ORDER BY Id DESC";
            var where = $"where Type={query.Type.Value}";

            #region 条件
            if (!string.IsNullOrEmpty(query.Name))
            {
                where += string.Format(" And Name like'%{0}%'", query.Name);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, currentPageIndex, query.PageSize.Value);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<MerchantQueryResponse>();

                foreach (var item in list)
                {
                    if (!string.IsNullOrEmpty(item.ProxyId))
                    {
                        var ProxyIds = item.ProxyId.Split(',');
                        foreach (var item1 in ProxyIds)
                        {
                            var ProxyName = _dbSession.DbConnection.Query<string>("select Name from merchant where Id=@MerchantId", new { MerchantId = item1 });
                            item.ProxyName += ProxyName.FirstOrDefault() + ",";
                        }
                        item.ProxyName = item.ProxyName.TrimEnd(',');
                    }
                }

                return new PagedList<MerchantQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.CurrentPageIndex.Value,
                    TotalCount = count
                };
            }
        }
    }
}
